$(function() {
    addOnChangeEventsToUserFeatures();
    applyUserPreferences();
    setUpGetChumashTextHandler();
    
    //Creates the Amount of Chapters in Genesis(50) by default
    createChapterListSelectElement(50);
    
   //Create Options for Ajax Spinner
    var spinnerOpts = {
        lines: 13, // The number of lines to draw
        length: 20, // The length of each line
        width: 10, // The line thickness
        radius: 30, // The radius of the inner circle
        corners: 1, // Corner roundness (0..1)
        rotate: 0, // The rotation offset
        direction: 1, // 1: clockwise, -1: counterclockwise
        color: '#000', // #rgb or #rrggbb or array of colors
        speed: 1, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        className: 'spinner', // The CSS class to assign to the spinner
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        top: 'auto', // Top position relative to parent in px
        left: 'auto' // Left position relative to parent in px
    };
    
    function createChapterListSelectElement(numOfChapters){
        $('#ChapterSelect').html(createChapterListItems(parseInt(numOfChapters)));
    }
    
    function setUpGetChumashTextHandler(){
        $('#GetChumashTextBtn').click(function(){
            var spinner = new Spinner(spinnerOpts);
            $.ajax({
                url: 'ChumashText.jsp' ,
                type: 'POST',
                dataType: 'html',
                data: { BookName : $('#BookSelect').val(), Chapt : $('#ChapterSelect').val() } ,
                beforeSend: function(){
                    spinner.spin($('.ChumashTextContainer'));
                },
                success: function(data){
                    $('#ChumashTextContainer').html(data);
                    applyUserPreferences();
                    spinner.stop();
                },
                error: function(){
                    alert("There was an error processing your request.");
                }
            });
        });
    }
    
    function applyUserPreferences(){
        shoreshTooltipFeature();
        shoreshHoverFeature();
    }
    
    function addOnChangeEventsToUserFeatures(){
        $('#ShoreshTooltipFeature').change(function(){
            shoreshTooltipFeature();
        });
        
        $('#ShoreshHoverFeature').change(function(){
            shoreshHoverFeature();
        });
        
        $('#BookSelect').change(function(){
            //Get num of chapters and create li elements to populate #ChaptSelect
            $.ajax({
                url: 'NumOfChaptersInBook.jsp' ,
                type: 'POST',
                dataType: 'html',
                data: { BookName : $('#BookSelect').val()} ,
                success: function(data){
                    createChapterListSelectElement(data);
                },
                error: function(){
                    alert("There was an error processing your request.");
                }
            });
        });
    }
    
    function createChapterListItems(numOfChapters){
        var html = "";
        for (var i = 1; i <= numOfChapters; i++) {
            html += "<option value='" + i + "'>" + i + "</option>";
        }
        return html;
    }
    
    function shoreshHoverFeature(){
        var addFeature = $('#ShoreshHoverFeature').prop('checked');
        if (addFeature){
            createShoreshEffect();
        } else {
            deleteShoreshHoverFeature();
        }
    }
    
    function shoreshTooltipFeature(){
        var addFeature = $('#ShoreshTooltipFeature').prop('checked');
        if (addFeature){
            createShoreshTooltipFeature();
        } else {
            deleteShoreshTooltipFeature();
        }
    }
    
    function deleteShoreshTooltipFeature(){
        $('.PowerTip').powerTip('destroy');
    }
    
    function createShoreshTooltipFeature() {
        $('.PowerTip').data('powertip', function() {
            return 'Shoresh: ' + $(this).data('shoresh');
        });
        $('.PowerTip').powerTip();     
    }
    
    function createShoreshEffect() {
        var shoreshClasses = {};
        $('.Shoresh').each(function() {
            var shoresh = $(this).data('shoresh');
            if (!(shoresh in shoreshClasses)) {
                shoreshClasses[shoresh] = true;
                addShoreshHoverEffect(shoresh);
            }
        });
    }

    function addShoreshHoverEffect(shoresh) {
        var listOfShorushim = $("span[data-shoresh='" + shoresh + "']");
        listOfShorushim.on('mouseenter mouseleave', 
                    { elements: listOfShorushim }, toggleHighlightOnElements);
    }
    
    function toggleHighlightOnElements(event){
        event.data.elements.toggleClass("HoverEffect");
    }
    
    function deleteShoreshHoverFeature() {
        $("span.Shoresh").each(function(){
            $(this).off('mouseenter mouseleave', toggleHighlightOnElements);
        });
    }
});